package com.cqupt.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqupt.common.log.annotation.OperationLog;
import com.cqupt.pojo.Host;
import com.cqupt.pojo.Interface;
import com.cqupt.pojo.ResponseMessage;
import com.cqupt.service.HostService;
import com.cqupt.service.ItemService;
import com.cqupt.service.impl.HostServiceImpl;
import com.cqupt.service.impl.ItemServiceImpl;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.PageUtils;
import com.cqupt.utils.RegularMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.RouteMatcher;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@CrossOrigin
@RequestMapping("host")
@RestController
public class HostController {
    /**
     * 类加载时初始化设置：自动发现规则，设置状态为全部开启
     */
    static{
        HostService hostService = new HostServiceImpl();
        String token = APIUtils.getToken();

        // 获取指定模板下的发现规则
        String[] templateids = new String[]{"10001", "10229", "10081"};
        for (String templateid : templateids){
            List<Map<String, Object>> dRules = hostService.getDRulesByTemplateid(token, templateid);
            ArrayList<String> ruleids = new ArrayList<>();
            for (Map<String, Object> dRlue : dRules){
                ruleids.add((String) dRlue.get("itemid"));
            }
            int size = ruleids.size();
            String[] rulesArr = ruleids.toArray(new String[size]);

            // 设置发现规则状态
            hostService.activeDRulesByTemplateid(token, rulesArr);
        }
    }
    @Autowired
    private HostService hostService;
    @Autowired
    private ItemService itemService;

    /**
     * 修改主机所属用户信息
     * 请求方式-post
     * @param hostInfo
     * @return
     */
    @RequestMapping("/updateUser")
    public ResponseMessage updateUser(@RequestBody Host hostInfo){
        ResponseMessage responseMessage = new ResponseMessage();

        // 请求执行
        int flag = hostService.updateHostInfo(hostInfo);

        // 结果封装
        if (flag>0){
            responseMessage.setStatus(true);
        }else {
            responseMessage.setStatus(false);
        }
        return responseMessage;

    }

    /**
     * 根据主机hostid获取用户名及密码
     * 请求方式-get
     * @param hostId 主机hostid(String)-Not Null
     * @return
     */
    @RequestMapping("/getUserInfo")
    public ResponseMessage getUserInfo(@RequestParam("hostid")String hostId){
        // 执行请求
        Host host = hostService.getUserInfoById(hostId);

        // 返回结果封装
        ResponseMessage responseMessage = new ResponseMessage();
        HashMap<String, Object> result = new HashMap<>();
        if (null==host){
            return null;
        }else {
            result.put("username",host.getUserName());
            result.put("password",host.getPassword());
            responseMessage.setContent(result);
            responseMessage.setStatus(true);
            return responseMessage;
        }
    }

    /**
     * 获取所有主机组（创建主机时需要）
     * 请求方式-get
     * @return
     */
    @RequestMapping("/getAllGroups")
    public ResponseMessage getAllGroups(){
        // 获取令牌
        String token = APIUtils.getToken();

        // 执行请求
        List<Map<String, Object>> groups = hostService.getGroups(token);

        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("result", groups);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 查询所有主机详细信息
     * 请求方式-get
     * @param pageSize
     * @param currentPage
     * @param type
     * @param avail
     * @param queryString
     * @return
     */
    @RequestMapping("/getAllHosts")
    public ResponseMessage getAllHosts(@RequestParam("pageSize") String pageSize,@RequestParam("currentPage") String currentPage,
                                       @RequestParam("type") String type,@RequestParam("avail") String avail,
                                       @RequestParam("queryString") String queryString){
        // 获取令牌
        String token = APIUtils.getToken();

        // 显示查询的依据是主机名称或者是主机ip
        String filterQueryType = RegularMatcher.filterRE_matcher(queryString);
        List<Map<String,Object>> hosts = new ArrayList<>();
        List<String> queryFilterHostids = new ArrayList<>();

        // 依据主机名称查询过滤返回状态信息
        if (filterQueryType.equals("hostname")){
            hosts = hostService.getFilterAllHosts(token,type,avail,queryString);

        // 依据主机ip查询过滤返回信息
        }else if (filterQueryType.equals("ip")){
            queryFilterHostids = hostService.getAllHostsByIp(token,queryString);// 获取ip

            hosts = hostService.getFilterAllHosts_ip(token,type,avail,queryFilterHostids);// 依据IP返回所属主机其他状态信息
        }else {
            hosts = hostService.getFilterAllHosts(token,type,avail,null);
        }

        // 分页控制
        int pageSizeInt = Integer.parseInt(pageSize);
        int currentPageInt = Integer.parseInt(currentPage);
        int total = hosts.size(); //主机总数
        List<Map<String, Object>> hostsResult = new ArrayList<>();
        int lastIndex = PageUtils.getLastIndex(pageSizeInt,currentPageInt,total) ; //每次切换页面后，最后的下标
        List<String> hostids =new ArrayList<>();

        //获取hostids集合
        if (total != 0){
            //根据主机id查询每个主机的接口IP和端口号
            List<Map<String ,String>> inters = new ArrayList<>();
            for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
                Map<String, Object> host = hosts.get(i);
                String hostid = (String)host.get("hostid");
                Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
                List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
                String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
                String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
                Map<String, String> inter = new HashMap<>();
                inter.put(hostid, ip+":"+port);
                inters.add(inter);
                hostids.add(hostid);
            }
            //通过集合查询各个host对应的item数 key:hostid  value:itemCount
            //itemCountMap = hostService.getItemCount(token, hostids);
            for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
                //获取host对象
                Map<String, Object> host = hosts.get(i);
                String hostid = (String)host.get("hostid");
                Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
                List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
                String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
                String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
                host.put("hostIP",ip+":"+port);
                //host.put("itemCount",itemCountMap.get(hostid) );
                //type：主机、交换机、防火墙、单向网闸
                hostsResult.add(hosts.get(i));
            }
            //通过集合查询各个host对应的资产清单
            List<Map<String ,Object>> InventoryResult = new ArrayList<>();
            for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++) {
                //获取host对象
                Map<String, Object> host = hosts.get(i);
                String hostid = (String) host.get("hostid");
                Map<String, Object> hostInventory = hostService.getHostInventory(token, hostid);
                List<Map<String, Object>> InventoryInfo = (List<Map<String, Object>>) hostInventory.get("result");
                host.put("hostInventory",InventoryInfo.get(0));
                //type：主机、交换机、防火墙、单向网闸
                InventoryResult.add(hosts.get(i));
            }

            //封装返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("inventory", InventoryResult);
            result.put("hosts", hostsResult);
            result.put("total", total);
            result.put("interfaces", inters);
            ResponseMessage responseMessage = new ResponseMessage();
            responseMessage.setContent(result);
            return responseMessage;
        }else {
            //封装返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("inventory", null);
            result.put("hosts", null);
            result.put("total", 0);
            result.put("interfaces", null);
            ResponseMessage responseMessage = new ResponseMessage();
            responseMessage.setContent(result);
            return responseMessage;
        }
    }

    /**
     * 获得筛选后可用的主机
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping("/getAvailAllHosts")
    public ResponseMessage getAvailAllHosts(@RequestParam("pageSize")String pageSize,@RequestParam("currentPage") String currentPage){
        String token = APIUtils.getToken();
        //查询所有主机
        List<Map<String, Object>> hosts = hostService.getAvailableAllHosts(token);
        int pageSizeInt = Integer.parseInt(pageSize);
        int currentPageInt = Integer.parseInt(currentPage);
        int total = hosts.size(); //主机总数
        List<Map<String, Object>> hostsResult = new ArrayList<>();
        int lastIndex = PageUtils.getLastIndex(pageSizeInt,currentPageInt,total) ; //每次切换页面后，最后的下标
        List<String> hostids =new ArrayList<>();
        // Map itemCountMap = new HashMap();
        //获取hostids集合
        //根据主机id查询每个主机的接口IP和端口号
        List<Map<String ,String>> inters = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            Map<String, String> inter = new HashMap<>();
            inter.put(hostid, ip+":"+port);
            inters.add(inter);
            hostids.add(hostid);
        }

        //通过集合查询各个host对应的item数 key:hostid  value:itemCount
        //itemCountMap = hostService.getItemCount(token, hostids);
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            host.put("hostIP",ip+":"+port);
            //host.put("itemCount",itemCountMap.get(hostid) );
            //type：主机、交换机、防火墙、单向网闸
            hostsResult.add(hosts.get(i));
        }
        //通过集合查询各个host对应的资产清单
        List<Map<String ,Object>> InventoryResult = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++) {
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String) host.get("hostid");
            Map<String, Object> hostInventory = hostService.getHostInventory(token, hostid);
            List<Map<String, Object>> InventoryInfo = (List<Map<String, Object>>) hostInventory.get("result");
            host.put("hostInventory",InventoryInfo.get(0));
            //type：主机、交换机、防火墙、单向网闸
            InventoryResult.add(hosts.get(i));
        }
        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("inventory", InventoryResult);
        result.put("hosts", hostsResult);
        result.put("total", total);
        result.put("interfaces", inters);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 获得筛选后服务器主机
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping("/getServerAllHosts")
    public ResponseMessage getServerAllHosts(@RequestParam("pageSize")String pageSize,@RequestParam("currentPage") String currentPage){
        String token = APIUtils.getToken();
        //查询所有主机
        List<Map<String, Object>> hosts = hostService.getServerAllHosts(token);
        int pageSizeInt = Integer.parseInt(pageSize);
        int currentPageInt = Integer.parseInt(currentPage);
        int total = hosts.size(); //主机总数
        List<Map<String, Object>> hostsResult = new ArrayList<>();
        int lastIndex = PageUtils.getLastIndex(pageSizeInt,currentPageInt,total) ; //每次切换页面后，最后的下标
        List<String> hostids =new ArrayList<>();
        // Map itemCountMap = new HashMap();
        //获取hostids集合
        //根据主机id查询每个主机的接口IP和端口号
        List<Map<String ,String>> inters = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            Map<String, String> inter = new HashMap<>();
            inter.put(hostid, ip+":"+port);
            inters.add(inter);
            hostids.add(hostid);
        }
        //通过集合查询各个host对应的item数 key:hostid  value:itemCount
        //itemCountMap = hostService.getItemCount(token, hostids);
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            host.put("hostIP",ip+":"+port);
            //host.put("itemCount",itemCountMap.get(hostid) );
            //type：主机、交换机、防火墙、单向网闸
            hostsResult.add(hosts.get(i));
        }
        //通过集合查询各个host对应的资产清单
        List<Map<String ,Object>> InventoryResult = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++) {
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String) host.get("hostid");
            Map<String, Object> hostInventory = hostService.getHostInventory(token, hostid);
            List<Map<String, Object>> InventoryInfo = (List<Map<String, Object>>) hostInventory.get("result");
            host.put("hostInventory",InventoryInfo.get(0));
            //type：主机、交换机、防火墙、单向网闸
            InventoryResult.add(hosts.get(i));
        }


        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("inventory", InventoryResult);
        result.put("hosts", hostsResult);
        result.put("total", total);
        result.put("interfaces", inters);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 获得筛选后除服务器外的主机
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping("/getOtherAllHosts")
    public ResponseMessage getOtherAllHosts(@RequestParam("pageSize")String pageSize,@RequestParam("currentPage") String currentPage){
        String token = APIUtils.getToken();
        //查询所有主机
        List<Map<String, Object>> hosts = hostService.getOtherAllHosts(token);
        int pageSizeInt = Integer.parseInt(pageSize);
        int currentPageInt = Integer.parseInt(currentPage);
        int total = hosts.size(); //主机总数
        List<Map<String, Object>> hostsResult = new ArrayList<>();
        int lastIndex = PageUtils.getLastIndex(pageSizeInt,currentPageInt,total) ; //每次切换页面后，最后的下标
        List<String> hostids =new ArrayList<>();
        // Map itemCountMap = new HashMap();
        //获取hostids集合
        //根据主机id查询每个主机的接口IP和端口号
        List<Map<String ,String>> inters = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            Map<String, String> inter = new HashMap<>();
            inter.put(hostid, ip+":"+port);
            inters.add(inter);
            hostids.add(hostid);
        }
        //通过集合查询各个host对应的item数 key:hostid  value:itemCount
        //itemCountMap = hostService.getItemCount(token, hostids);
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            host.put("hostIP",ip+":"+port);
            //host.put("itemCount",itemCountMap.get(hostid) );
            //type：主机、交换机、防火墙、单向网闸
            hostsResult.add(hosts.get(i));
        }
        //通过集合查询各个host对应的资产清单
        List<Map<String ,Object>> InventoryResult = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++) {
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String) host.get("hostid");
            Map<String, Object> hostInventory = hostService.getHostInventory(token, hostid);
            List<Map<String, Object>> InventoryInfo = (List<Map<String, Object>>) hostInventory.get("result");
            host.put("hostInventory",InventoryInfo.get(0));
            //type：主机、交换机、防火墙、单向网闸
            InventoryResult.add(hosts.get(i));
        }


        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("inventory", InventoryResult);
        result.put("hosts", hostsResult);
        result.put("total", total);
        result.put("interfaces", inters);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 获得筛选后不可用的主机
     * 请求方式-get
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping("/getUnAvailAllHosts")
    public ResponseMessage getUnAvailAllHosts(@RequestParam("pageSize")String pageSize,@RequestParam("currentPage") String currentPage){
        String token = APIUtils.getToken();
        //查询所有主机
        List<Map<String, Object>> hosts = hostService.getUnAvailableAllHosts(token);
        int pageSizeInt = Integer.parseInt(pageSize);
        int currentPageInt = Integer.parseInt(currentPage);
        int total = hosts.size(); //主机总数
        List<Map<String, Object>> hostsResult = new ArrayList<>();
        int lastIndex = PageUtils.getLastIndex(pageSizeInt,currentPageInt,total) ; //每次切换页面后，最后的下标
        List<String> hostids =new ArrayList<>();
        // Map itemCountMap = new HashMap();
        //获取hostids集合
        //根据主机id查询每个主机的接口IP和端口号
        List<Map<String ,String>> inters = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            Map<String, String> inter = new HashMap<>();
            inter.put(hostid, ip+":"+port);
            inters.add(inter);
            hostids.add(hostid);
        }
        //通过集合查询各个host对应的item数 key:hostid  value:itemCount
        //itemCountMap = hostService.getItemCount(token, hostids);
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++){
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String)host.get("hostid");
            Map<String, Object> hostInterfaces = hostService.getHostInterfaces(token, hostid);
            List<Map<String, Object>> interfaceInfo = (List<Map<String, Object>>)hostInterfaces.get("result");
            String ip = interfaceInfo.size()>0?interfaceInfo.get(0).get("ip").toString():"设";
            String port = interfaceInfo.size()>0?interfaceInfo.get(0).get("port").toString():"备";
            host.put("hostIP",ip+":"+port);
            //host.put("itemCount",itemCountMap.get(hostid) );
            //type：主机、交换机、防火墙、单向网闸
            hostsResult.add(hosts.get(i));
        }
        //通过集合查询各个host对应的资产清单
        List<Map<String ,Object>> InventoryResult = new ArrayList<>();
        for (int i = pageSizeInt*(currentPageInt - 1);i<=lastIndex;i++) {
            //获取host对象
            Map<String, Object> host = hosts.get(i);
            String hostid = (String) host.get("hostid");
            Map<String, Object> hostInventory = hostService.getHostInventory(token, hostid);
            List<Map<String, Object>> InventoryInfo = (List<Map<String, Object>>) hostInventory.get("result");
            host.put("hostInventory",InventoryInfo.get(0));
            //type：主机、交换机、防火墙、单向网闸
            InventoryResult.add(hosts.get(i));
        }


        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("inventory", InventoryResult);
        result.put("hosts", hostsResult);
        result.put("total", total);
        result.put("interfaces", inters);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 获取某个主机的信息(byHostid)
     * 请求方式-get
     * @param hostid
     * @return
     */
    @RequestMapping("/getHostByHostid")
    public ResponseMessage getHostByHostid(String hostid) {
        // 获取令牌
        String token = APIUtils.getToken();

        // 依据主机id获取主机信息
        List<Map<String, Object>> result = hostService.getHostByHostid(token, hostid);

        // 获取主机关联用户名及密码
        Host host = hostService.getUserInfoById(hostid);
        Map<String, Object> resultMap = result.get(0);
        if (null!=host){
            resultMap.put("username",host.getUserName());
            resultMap.put("password",host.getPassword());
        }

        //封装返回结果
        ResponseMessage responseMessage = new ResponseMessage();
        if(result.size() > 0){
            responseMessage.setStatus(true);
            responseMessage.setContent(resultMap);
        }else{
            responseMessage.setStatus(false);
        }
        return responseMessage;
    }

    /**
     * 获取所有模板的详细信息
     * 请求方式-get
     * @return
     */
    @RequestMapping("/getTemplates")
    public ResponseMessage getTemplates(){
        // 获取令牌
        String token = APIUtils.getToken();

        // 模板请求
        List<Map<String, Object>> templates = hostService.getTemplates(token);

        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("result", templates);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 创建主机
     * 请求方式-post
     * @param body
     * @return
     */
    @OperationLog(level = "信息", object = "设备", operationType = "新增")
    @RequestMapping("/createHost")
    public ResponseMessage createHost(@RequestBody Map<String, Object> body){
        String token = APIUtils.getToken();
        // 获取参数信息
        String host = (String) body.get("host");// 设备名称
        String description = (String) body.get("description");
        if(description == null)
            description = "";

        // 服务器需要（网络设备不需要）
        String username = (String) body.get("username");
        String password = (String) body.get("password");

        //获取硬件设备信息（可选项）
        String hostType = (String) body.get("hostType");// 设备型号
        String cpuType = (String) body.get("cpuType");
        String memory = (String) body.get("memory");// 内存品牌
        HashMap<String, String> inventory = new HashMap<>();
        inventory.put("hostType",hostType=(hostType==null?" ":hostType));
        inventory.put("cpuType",cpuType=(cpuType==null?" ":cpuType));
        inventory.put("memory",memory=(memory==null?" ":memory));

        String systemType = (String) body.get("systemType");// 操作系统类型 1 Linux 2 windows

        String ip = (String) body.get("ip");
        String port = (String) body.get("port");

        String dns = (String) body.get("dns");// 可选
        if(dns == null)
            dns = "";

        Integer type = Integer.parseInt((String)body.get("type"));// 设备类型

        Integer main = 1;
        // 停止使用DNS链接主句、默认使用IP
        Integer useip = 1;
        Interface inter = null;

        // type为1表示类型为服务器，否则为网络设备
        if(type == 1){
            inter = new Interface(dns, ip, port, main, type, useip);
        }else{
            Integer version = Integer.parseInt((String)body.get("version"));
            String community = (String) body.get("community");
            String bulk = "1";
            inter = new Interface(dns, ip, port, main, type, useip, version, community, Integer.parseInt(bulk));
        }
        //发送创建请求，获得结果
        Map<String, Object> result = hostService.addHost(token, host, description, inter, systemType,inventory);
        JSONObject result1 = (JSONObject) result.get("result");
        if(result1 != null){
            JSONArray hostids = (JSONArray) result1.get("hostids");
            String hostid = (String) hostids.get(0);

            // 主机信息插入数据库
            if(type == 1){
                Host host_tb = new Host(hostid, username, password);
                hostService.insertHostInfo(host_tb);
            }

            //根据hostid和类型获取自动发现规则
            List<Map<String, Object>> dRulesOn = hostService.getActiveDRulesByHostid(token, hostid,systemType);
            //将获取的自动发现规则的itemid全部获取
            ArrayList<String> ruleIdsOn = new ArrayList<>();
            for (Map<String, Object> dRlue : dRulesOn){
                ruleIdsOn.add((String) dRlue.get("itemid"));
            }
            int sizeOn = ruleIdsOn.size();
            String[] rulesArrOn = ruleIdsOn.toArray(new String[sizeOn]);
            //设自动发现规则delay为1s
            Map<String, Object> rec01 = hostService.DRulesChecknow(token, rulesArrOn);
            //设置系统描述更新间隔2s，为了尽快获得系统描述(仅限非SNMP设备)
            if (type == 1){
                itemService.setSystemDescDelayAs2s(token,hostid);
            }
            //设置延时3分钟，随后delay设为初始值1h
            Timer time = new Timer();
            time.schedule(new TimerTask() {
                @Override
                public void run() {
                    Map<String, Object> rec02 = hostService.DRulesReset(token, rulesArrOn);
                    if(type == 1){
                        itemService.resetSystemDescDelay(token,hostid);
                    }
                }
            }, 180000);
        }

        //封装返回结果
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> info = new HashMap<>();
        info.put("log_objectName",host);
        if (result.get("result") != null){
            responseMessage.setStatus(true);
            info.put("log_description","");
            info.put("message", "添加设备 "+host+" 成功");
        }else {
            responseMessage.setStatus(false);
            info.put("message", result.get("error"));
            responseMessage.setErrorCode((String) result.get("error"));
        }
        responseMessage.setContent(info);
        return responseMessage;
    }

    /**
     * 删除主机
     * 请求方式-get
     * @param hostid 主机id
     * @param hostName 主机名
     * @return
     */
    @OperationLog(level = "信息", object = "设备", operationType = "删除")
    @RequestMapping("/deleteHost")
    public ResponseMessage deleteHost(@RequestParam(value = "hostid") String hostid,
                                      @RequestParam(value = "name") String hostName){
        String token = APIUtils.getToken();

        //获得结果
        Map<String, Object> result = hostService.deleteHost(token, hostid);

        //封装返回结果
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> info = new HashMap<>();
        info.put("log_objectName",hostName);
        if (result.get("result") != null){
            responseMessage.setStatus(true);
            info.put("message", "删除成功");
            info.put("log_description","");
        }else{
            responseMessage.setStatus(false);
            info.put("message", "删除失败");
            responseMessage.setErrorCode("");
        }
        responseMessage.setContent(info);
        return responseMessage;
    }

    /**
     * 根据主机hostid获取主机运行状态信息
     * 请求方式-get
     * @param host
     * @return
     */
    @RequestMapping("/getHostStatus")
    public ResponseMessage getHostStatus(@RequestParam("host") String host){
        // 令牌获取
        String token = APIUtils.getToken();

        List<Map<String, Object>> status = hostService.getHostStatusById(token, host);

        ResponseMessage responseMessage = new ResponseMessage();
        if(status != null && status.size() > 0){
            Map<String, Object> statusMap = status.get(0);
            responseMessage.setStatus(true);
            responseMessage.setContent(statusMap);
        }else{
            responseMessage.setStatus(false);
        }
        return responseMessage;
    }

    /**
     * 新增根据hostid同时查询多个主机的状态信息
     * @param params hostids(Array[String])
     * @return List<Map<String,String>>
     */
    @RequestMapping("/getHostStatusByHostid")
    public ResponseMessage getHostStatusByHostid(@RequestBody Map<String,Object> params){
        // 参数转换
        List<String> hostids = (List<String>) params.get("hostids");
        List<Map<String, Object>> status = hostService.getHostStatusById(hostids);

        // 结果封装
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> result = new HashMap<>();
        result.put("result", status);
        responseMessage.setContent(result);
        responseMessage.setStatus(true);
        return responseMessage;
    }

    /**
     * 获取与某个主机关联的所有模板、主机组以及接口信息
     * @param hostId 主机hostid
     * @param host 主机名称
     * @return
     */
    @RequestMapping("/getHostTempGrou")
    public ResponseMessage getHostTemplates(String hostId,String host){
        String token = APIUtils.getToken();
        // 获得模板
        List<Map<String, Object>> templates = hostService.getHostTemplates(token,hostId);
        // 获得主机组
        List<Map<String, Object>> groups = hostService.getHostGroups(token,host);
        // 获得接口
        Map<String, Object> interfaces = hostService.getHostInterfaces(token,hostId);
        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("templates", templates);
        result.put("groups", groups);
        result.put("interfaces", interfaces);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 更新主机信息
     * 请求方式-post
     * @param body
     * @return
     */
    @OperationLog(level = "信息", object = "设备", operationType = "修改")
    @RequestMapping("/updateHost")
    public ResponseMessage updateHost(@RequestBody Map<String, Object> body){
        String token = APIUtils.getToken();

        // 参数封装
        String host = (String) body.get("host");
        String hostid = (String) body.get("hostid");
        String description = (String) body.get("description");

        // 主机接口信息封装
        String ip = (String) body.get("ip");
        String dns = (String) body.get("dns");
        if(dns == null)
            dns = "";
        String port = (String) body.get("port");
        Integer type = Integer.parseInt((String)body.get("type"));
        Integer main = 1;
        String useripStr = (String)body.get("useip");
        int useip = 0;
        if(useripStr.equals("IP"))
            useip = 1;
        Interface inter = null;

        // type为1表示agent接口构造，否则为SNMP接口的构造
        if(type == 1) {
            inter = new Interface(dns, ip, port, main, type, useip);
        }else {
            Integer version = Integer.parseInt((String)body.get("version"));
            String community = (String) body.get("community");
            String bulk = "1";
            inter = new Interface(dns, ip, port, main, type, useip, version, community, Integer.parseInt(bulk));
        }

        // 执行更新
        Map<String, Object> result = hostService.updateHost(token, hostid, host, inter, description);

        //封装返回结果
        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> info = new HashMap<>();
        info.put("log_objectName",host);
        if (result.get("result") != null){
            responseMessage.setStatus(true);
            info.put("log_description","");
            info.put("message", "修改设备 "+host+" 成功");
        }else {
            responseMessage.setStatus(false);
            info.put("message", result.get("error"));
            responseMessage.setErrorCode((String) result.get("error"));
        }
        responseMessage.setContent(info);
        return responseMessage;
    }

    /**
     * 只查询所有主机
     * 请求方式-get
     * @return
     */
    @RequestMapping("/findAllHost")
    public ResponseMessage findAllHost(){
        String token = APIUtils.getToken();
        //查询所有主机
        List<Map<String, Object>> hosts = hostService.getAllHosts(token,"0","0");
        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("hosts", hosts);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 查询主机的资产清单
     * @param host
     * @return
     */
    @RequestMapping("/findInventory")
    public ResponseMessage findInventoryById(@RequestParam("host") String host){
        String token = APIUtils.getToken();
        //查询所有主机
        Map<String, Object> Inventory = hostService.getHostInventory(token,host);
        List<Map<String, Object>> details = (List<Map<String, Object>>) Inventory.get("result");
        Map<String, Object> rec = (Map<String, Object>) details.get(0);
        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("Inventory", rec.get("inventory"));
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 根据主机id判断其系统类型
     * 其中 => 0-windows；1-Linux；2-网络设备类型
     * @param hostid
     * @return
     */
    @RequestMapping("/checkHostSystemType")
    public ResponseMessage checkHostSystemType(@RequestParam("hostid") String hostid){
        //查询所有主机
        int flag = hostService.checkSystemType(hostid);
        //封装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("systemType", flag);
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 用于拓扑图运行视图-获取某个主机的各项运行指标
     *  如: 设备名称,设备状态,内存,磁盘,cpu利用率等
     * @param params hostid(String)
     * @return Map<String,Object>
     */
    @RequestMapping("getHostRunDetailsByHostid")
    public ResponseMessage getHostRunDetailsByHostid(@RequestBody Map<String,Object> params){
        String hostid = (String) params.get("hostid");

        // 获取数据
        Map<String,Object> hostRunData = hostService.getHostRunDateils(hostid);

        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> result = new HashMap<>();
        result.put("result", hostRunData);
        responseMessage.setContent(result);
        return responseMessage;
    }

    /**
     * 获取主机信息接口 2022.05.25需求
     * @param
     * @return
     */
    @RequestMapping("getHostRunDetails_api")
    public ResponseMessage getHostRunDetails_api(){

        // 获取数据
        Map<String,Object> hostRunData = hostService.getHostRunDateils_api();

        ResponseMessage responseMessage = new ResponseMessage();
        Map<String, Object> result = new HashMap<>();
        result.put("result", hostRunData);
        responseMessage.setContent(result);
        responseMessage.setStatus(true);
        return responseMessage;
    }
}
